package com.example.demo.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.example.demo.dto.ResponseDTO;
import com.example.demo.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@Controller
@RequestMapping(value = "user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("doLogin")
    @ResponseBody
    public ResponseDTO<?> doLogin(String username, String password) {
        User user = userService.queryByName(username);
        if(user == null) {
            return ResponseDTO.error("未查询到用户名");
        }
        String salt = user.getSalt();
        String inputPassword = BCrypt.hashpw(password,salt);

        log.info("oriPassword:{},encodePassword:{},storePassword:{}",password,inputPassword,user.getPassword());

        if(user.getPassword().equals(inputPassword)) {
            StpUtil.login(user.getId());
            UserDTO userDTO = new UserDTO();
            userDTO.setUserId(user.getId());
            userDTO.setUsername(user.getUsername());
            userDTO.setNickname(user.getNickname());
            return ResponseDTO.ok(userDTO);
        } else {
            return ResponseDTO.error("密码错误");
        }
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    @ResponseBody
    public ResponseDTO<?> isLogin() {
        return ResponseDTO.ok(StpUtil.isLogin());
    }

    @GetMapping("logout")
    public ResponseDTO<?> logout() {
        if(StpUtil.isLogin()) {
            StpUtil.logout();
        }
        return ResponseDTO.ok();
    }

    public static void main(String[] args) {
        String password = "123";
        String salt = BCrypt.gensalt();
        System.out.println("password:"+password);
        System.out.println("salt:"+salt);
        System.out.println("encodePassword:"+BCrypt.hashpw(password,salt));
    }


}
